package dispatcher;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import services.CompanyService;
import services.PollService;
import services.ValidationService;
import utils.MyBase64;
import utils.Utils;
import business.CompanyCampaign;
import business.FormMovement;
import business.ValidationError;
import business.ValidationReason;

public class GetJsonGrid extends HttpServlet{

	private static final String GET_VALIDATION_ERRORS = "GET_VE";
	private static final String GET_COMPANY_CAMPAIGNS = "GET_CC";
	private static final String GET_REJECT_COMMENTS = "GET_RC";
	private static final String GET_VALIDATION_OPTIONS = "GET_VO";
	
	private static final long serialVersionUID = -3880714005446692534L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			getGrid(req, resp);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			getGrid(req, resp);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
		
	protected void getGrid(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, JSONException {
		HttpSession session = request.getSession(true);
		Object userID = session.getAttribute("userID");
		Object sessionCompanyCampaignID = session.getAttribute("companyCampaign");
		if(userID == null || userID.toString().trim().length() == 0)
		{
			response.sendRedirect("./login?option=" + MyBase64.encode(Login.NO_SESSION.getBytes()));
		}
		else
		{
			String gridName = request.getParameter("gridName");
			
			response.setContentType("text/html;charset=ISO-8859-1");
			response.setCharacterEncoding("UTF-8");
			PrintWriter writer = response.getWriter();
			
			if(gridName.equals(GET_COMPANY_CAMPAIGNS))
			{
				List<CompanyCampaign> pollCampaignList = new CompanyService().getCompanyCampaignsByUser(Long.valueOf(userID.toString()));
				JSONObject jsonObj = new JSONObject();
				jsonObj.put("page","1");
				jsonObj.put("total","1");
				jsonObj.put("records", pollCampaignList.size());
				
				JSONArray array = new JSONArray();
				for(CompanyCampaign pollCampaign : pollCampaignList)
				{
					String companyCampaignID = pollCampaign.getId().toString();
					
					JSONObject jsonDatos = new JSONObject();
					jsonDatos.put("id", companyCampaignID);
					JSONArray arrayCell = new JSONArray();
					arrayCell.put(pollCampaign.getCompany().getCuit());
					arrayCell.put(pollCampaign.getCampaign().getDescription());
					arrayCell.put(pollCampaign.getPollStatus().getStatus());
					arrayCell.put("<img alt=\"Status\" border=\"0\" src=\"styles/img/download.png\" width=\"16\" height=\"16\">");
					arrayCell.put("<img alt=\"Status\" border=\"0\" src=\"styles/img/upload.png\" width=\"16\" height=\"16\">");
					jsonDatos.put("cell", arrayCell);

					array.put(jsonDatos);
				}
				jsonObj.put("rows",array);
				writer.print(jsonObj.toString());
			}
			else if(gridName.equals(GET_VALIDATION_ERRORS))
			{
				Long companyCampaignID = Long.valueOf(sessionCompanyCampaignID.toString());
				List<ValidationError> validationErrorList = new ValidationService().getValidationErrorsByCompanyCampaignIDOrderByErrors(companyCampaignID);
				JSONObject jsonObj = new JSONObject();
				jsonObj.put("page","1");
				jsonObj.put("total","1");
				jsonObj.put("records", validationErrorList.size());
				
				JSONArray array = new JSONArray();
				StringBuilder strParams = null;
				for(ValidationError validationError : validationErrorList)
				{
					String validationErrorID = validationError.getId().toString();
					
					JSONObject jsonDatos = new JSONObject();
					jsonDatos.put("id", validationErrorID);
					JSONArray arrayCell = new JSONArray();
					String img = null;
					
					if(validationError.getValidation().getValidationType().getId() == ValidationService.WARNING_TYPE_ID)
					{
						img = "<img id=\"validationType\" alt=\"Validation\" border=\"0\" src=\"styles/img/warning_16.png\" width=\"12\" height=\"12\">";
					}
					else if(validationError.getValidation().getValidationType().getId() == ValidationService.ERROR_TYPE_ID)
					{
						img = "<img id=\"validationType\" alt=\"Validation\" border=\"0\" src=\"styles/img/error_16.png\" width=\"12\" height=\"12\">";
					}
					
					arrayCell.put(img);
					arrayCell.put(validationError.getValidation().getValidationType().getId());
					arrayCell.put(validationError.getValidation().getValidationType().getDescription());
					arrayCell.put(Utils.getLocalLabel(validationError.getCompanyPoll().getLocal()));
					arrayCell.put(validationError.getCompanyPoll().getPoll().getName());
					arrayCell.put(validationError.getValidation().getCode());
					arrayCell.put(validationError.getValidation().getDescription());
					arrayCell.put(validationError.getValidation().getId());
					
					ValidationReason validationReason = validationError.getValidationReason();
					if(validationReason != null)
					{
						arrayCell.put(validationReason.getDescription());	
					}
					else
					{
						arrayCell.put("");	
					}					
					
					arrayCell.put(validationError.getObservations());
					strParams = new StringBuilder();
					strParams.append(companyCampaignID);
					strParams.append("|");
					strParams.append(validationError.getCompanyPoll().getPoll().getId());
					strParams.append("|");
					if(validationError.getCompanyPoll().getLocal() == null)
					{
						strParams.append("0");
					}
					else
					{
						strParams.append(validationError.getCompanyPoll().getLocal().getId());
					}					
					arrayCell.put(MyBase64.encode(strParams.toString().getBytes("UTF-8")));
					jsonDatos.put("cell", arrayCell);

					array.put(jsonDatos);
				}
				jsonObj.put("rows",array);
				writer.print(jsonObj.toString());
			}
			else if(gridName.equals(GET_REJECT_COMMENTS))
			{
				Long companyCampaignID = Long.valueOf(sessionCompanyCampaignID.toString());
				List<FormMovement> formMovementList = new PollService().getFormMovementsNotApprovedByCompanyCampaign(companyCampaignID);
				JSONObject jsonObj = new JSONObject();
				jsonObj.put("page","1");
				jsonObj.put("total","1");
				jsonObj.put("records", formMovementList.size());
				
				JSONArray array = new JSONArray();
				for(FormMovement formMovement : formMovementList)
				{
					String formMovementID = formMovement.getId().toString();
					
					JSONObject jsonDatos = new JSONObject();
					jsonDatos.put("id", formMovementID);
					JSONArray arrayCell = new JSONArray();			
									
					arrayCell.put(Utils.getLocalLabel(formMovement.getCompanyPoll().getLocal()));
					arrayCell.put(formMovement.getCompanyPoll().getPoll().getName());
					arrayCell.put(Utils.convertDateToString(formMovement.getDate()));
					arrayCell.put(formMovement.getObservations());
					
					jsonDatos.put("cell", arrayCell);

					array.put(jsonDatos);
				}
				jsonObj.put("rows",array);
				writer.print(jsonObj.toString());
			}
			else if(gridName.equals(GET_VALIDATION_OPTIONS))
			{
				Long validationID = Long.valueOf(request.getParameter("validationID"));
				List<ValidationReason> validationReasons = new ValidationService().getValidationReasonsByValidationID(validationID);
				
				StringBuilder strBld = new StringBuilder();
				strBld.append("<select style=\"width:200px.\">");
				
				for(ValidationReason validationReason : validationReasons)
				{	strBld.append("<option value='");
					strBld.append(validationReason.getId().toString());
					strBld.append("'>");
					strBld.append(validationReason.getDescription());
					strBld.append("</option>");
//					String vrID = validationReason.getId().toString();
//					validationReason.getDescription();
				}
				writer.print(strBld.toString());
			}
			else
			{
				System.out.println(request.getParameter("observation"));
				System.out.println(request.getParameter("id"));
			}
		}
	}
}
